<template>
  <div class="qualityPlanDetailDiv">
    <Splitpanes class="area">
      <Pane size="50">
        <vxe-toolbar perfect>
          <template #buttons>
            <vxe-button type="text" class="button-blue" icon="vxe-icon-square-plus" content="新建" @click="handleAdd(-1)"></vxe-button>
            <vxe-button type="text" icon="vxe-icon-save" class="button-blue" content="保存" @click="saveDetail"></vxe-button>
            <vxe-button type="text" icon="vxe-icon-delete" class="button-red" content="删除" @click="handleDelete"></vxe-button>
          </template>
        </vxe-toolbar>
        <div class="tableBody">
          <vxe-table ref="qualityPlanDetailTableRef" :loading="showLoading" @current-change="currentChangeEvent" class="mytable-scrollbar" border align="left" height="auto" :keep-source="true" :data="qualityPlanDetailList" :row-config="{ isCurrent: true, isHover: true }" :edit-config="{ trigger: 'click', mode: 'cell', showIcon: false }" resizable show-overflow>
            <vxe-column type="checkbox" align="center" width="26"></vxe-column>
            <vxe-column type="seq" title="序号" align="center" width="30"></vxe-column>
            <vxe-column field="detailCode" title="明细编码" width="50" :edit-render="{ autofocus: '.vxe-input--inner' }">
              <template #edit="{ row }">
                <vxe-input v-model="row.detailCode" type="text"></vxe-input>
              </template>
            </vxe-column>
            <vxe-column field="detailTitle" title="明细标题" width="200" :edit-render="{ autofocus: '.vxe-input--inner' }">
              <template #edit="{ row }">
                <vxe-input v-model="row.detailTitle" type="text"></vxe-input>
              </template>
            </vxe-column>
            <vxe-column field="startDate" title="开始时间" align="center" :edit-render="{ autofocus: '.vxe-input--inner' }">
              <template #edit="{ row }">
                <vxe-input v-model="row.startDate" type="date"></vxe-input>
              </template>
            </vxe-column>
            <vxe-column field="endDate" title="结束时间" align="center" :edit-render="{ autofocus: '.vxe-input--inner' }">
              <template #edit="{ row }"> <vxe-input v-model="row.endDate" type="date"></vxe-input> </template
            ></vxe-column>
            <vxe-column field="nodeName" title="附件类型" align="center" :edit-render="{ autofocus: '.vxe-input--inner' }">
              <template #default="{ row }">
                {{ row.nodeName }}
              </template>
              <template #edit="{ row }">
                <vxe-select v-model="row.nodeId" placeholder="附件" value-key="id" size="mini">
                  <vxe-option v-for="node in nodeList" :key="node.id" :value="node.id" :label="node.name"></vxe-option>
                </vxe-select> </template
            ></vxe-column>
          </vxe-table>
        </div>
      </Pane>
      <Pane size="50">
        <vxe-toolbar perfect>
          <template #buttons>
            <el-upload action="" v-show="showUpload" :http-request="onUpload" :before-upload="beforeAvatarUpload" :show-file-list="false" :limit="fileLimit" class="attachmentAddressUpload">
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
            <vxe-button type="text" icon="vxe-icon-delete" class="button-red" content="删除" @click="deleteAnnex"></vxe-button>
          </template>
        </vxe-toolbar>
        <vxe-table ref="groupTable" border="inner" align="left" class="mytable-scrollbar" height="auto" :data="groupFormulaList" resizable show-overflow keep-source>
          <vxe-column type="checkbox" width="30px"></vxe-column>
          <vxe-column field="rawFileName" title="原文件名"></vxe-column>
          <vxe-column field="fileType" title="文件类型"></vxe-column>
          <vxe-column field="rawFileName" title="查看">
            <template #default="{ row }">
              <el-image v-show="row.fileType === 'image/png'" style="width: 100px; height: 100px" :src="row.fileUrl" :preview-src-list="[row.fileUrl]" :zoom-rate="1.2" :max-scale="7" :min-scale="0.2" :initial-index="4" fit="cover" />
              <vxe-button mode="text" icon="vxe-icon-eye-fill" @click="showPdf(row)"></vxe-button>
            </template>
          </vxe-column>
        </vxe-table>
        <el-dialog title="图片详情" :show-close="true" v-model="showTemplateDialog" class="imgDetailDialog" top="6vh" :close-on-click-modal="false" width="1500px">
          <vue-pdf-app :pdf="pdfUrl"></vue-pdf-app>
        </el-dialog>
      </Pane>
    </Splitpanes>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, getCurrentInstance, defineExpose, onMounted } from 'vue';
import { VxeMessage, VxeNotifyType } from '@/utils/CommonMessage';
import { View } from '@element-plus/icons-vue';
import { Splitpanes, Pane } from 'splitpanes';
import VuePdfApp from 'vue3-pdf-app';
import 'vue3-pdf-app/dist/icons/main.css';

defineExpose({ dbDetailModel, clearData });

let { proxy }: any = getCurrentInstance();
let currentPlanInfo = reactive({});
let showLoading = ref(false);
let qualityPlanDetailList = reactive([]);
let fileLimit = ref(2);
let groupFormulaList: any = reactive([]); //表格列表
let pdfUrl = ref('');
let showTemplateDialog = ref(false);
let currentDetailInfo = reactive({
  id: '',
  nodeId: ''
});
let nodeList = reactive([]);
let nodeMap = ref(new Map());
let nodeCount = ref(3);
let showUpload = ref(true);

onMounted(() => {
  findNodeList();
});

//查询计划详情
function dbDetailModel(row: any) {
  qualityPlanDetailList.length = 0;
  Object.assign(currentPlanInfo, row);
  const url = '/wk/quality/detail/getQualityDetailList';
  proxy.$http
    .get(url, { params: { planId: row.id } })
    .then((res: any) => {
      if (res.data && res.data.length > 0) {
        qualityPlanDetailList.push(...res.data);
        currentChangeEvent({ row: qualityPlanDetailList[0] });
        const $xTable = proxy.$refs.qualityPlanDetailTableRef as any;
        if ($xTable) {
          $xTable.setCurrentRow(qualityPlanDetailList[0]);
        }
      }
    })
    .catch((err: any) => {
      proxy.$alert(err, '提示');
    });
}

// 获取节点字典列表
function findNodeList() {
  nodeList.length = 0;
  const url = '/wk/quality/node/list';
  proxy.$http
    .get(url, {})
    .then((res: any) => {
      if (res.data && res.data.length > 0) {
        nodeList.push(...res.data);
        nodeList.forEach((item) => {
          nodeMap.value.set(item.id, item);
        });
      }
    })
    .catch((err: any) => {
      proxy.$alert(err, '提示');
    });
}

// 添加
async function handleAdd(row?: number) {
  const $table = proxy.$refs.qualityPlanDetailTableRef as any;
  if ($table) {
    const record = {
      id: null,
      detailCode: '',
      detailTitle: '',
      startDate: '',
      endDate: '',
      annexPath: '',
      planId: currentPlanInfo.id
    };
    const { row: newRow } = await $table.insertAt(record, row);
    await $table.setEditRow(newRow);
  }
}

// 保存
function saveDetail() {
  const $table = proxy.$refs.qualityPlanDetailTableRef as any;
  const arrNews = $table.getInsertRecords();
  const arrModifies = $table.getUpdateRecords();
  arrNews.forEach((item: any, idx) => {
    const url = '/wk/quality/detail/addQualityDetail';
    const data = item;
    data.nodeName = nodeMap.value.get(data.nodeId).name;
    proxy.$http
      .post(url, data)
      .then((res: any) => {
        if (arrModifies.length <= 0 && idx === arrNews.length - 1) {
          VxeMessage('保存成功', VxeNotifyType.success);
        }
      })
      .catch((err) => {
        if (arrModifies.length <= 0 && idx === arrNews.length - 1) {
          VxeMessage('保存失败', VxeNotifyType.error);
        }
      });
  });
  arrModifies.forEach((item, idx) => {
    const url = '/wk/quality/detail/editQualityDetail';
    const data = item;
    data.nodeName = nodeMap.value.get(data.nodeId).name;
    proxy.$http
      .post(url, data)
      .then((res: any) => {
        if (idx === arrModifies.length - 1) {
          VxeMessage('保存成功', VxeNotifyType.success);
        }
      })
      .catch((err) => {
        if (idx === arrModifies.length - 1) {
          VxeMessage('保存失败', VxeNotifyType.error);
        }
      });
  });
}

// 删除
function handleDelete() {
  const $xTable = proxy.$refs.qualityPlanDetailTableRef as any;
  const selectRows = $xTable.getCheckboxRecords();
  if (selectRows.length <= 0) {
    VxeMessage('请先选中要删除的项', VxeNotifyType.warning);
    return;
  }
  proxy
    .$confirm('确定删除此项？', '提示', {
      cancelButtonClass: 'cancel-button',
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    .then((type) => {
      if (type === 'confirm') {
        let ids = selectRows.map((item) => item.id);
        const url = '/wk/quality/detail/deleteQualityDetail';
        proxy.$http
          .post(url, ids)
          .then((res: any) => {
            if (res.status.code === 1) {
              VxeMessage('删除成功', VxeNotifyType.success);
              dbDetailModel(currentPlanInfo);
            } else {
              VxeMessage('删除失败', VxeNotifyType.error);
            }
          })
          .catch((err) => {
            VxeMessage(err.response.data.status.msg, VxeNotifyType.error);
          });
      }
    });
}
function beforeAvatarUpload(rawFile) {
  if (rawFile.type.split('/')[0] === 'image' || rawFile.type === 'application/pdf') {
    if (rawFile.size < 20 * 1024 * 1024) {
      return true;
    }
  }
  VxeMessage('文件大小或格式不正确！', VxeNotifyType.error);
  return false;
}

function currentChangeEvent(row: any) {
  Object.assign(currentDetailInfo, row.row);
  getAnnexList();
}

function onUpload(rawFile) {
  const rawFileName = rawFile.file.name;
  const suffix = rawFileName.substring(rawFileName.lastIndexOf('.'));
  const fileName = new Date().getTime().toString() + suffix;
  let formData = new FormData();
  formData.append('file', rawFile.file, fileName);
  proxy.$http
    .post((window as any).apiUrl.VITE_SERVER_URL + '/file/upload', formData, { headers: { 'Content-Type': 'multipart/form-data' } })
    .then((res) => {
      if (res.status.code == 1) {
        const fileUrl = (window as any).apiUrl.VITE_SERVER_URL + '/file/reload/' + fileName;
        const fileDataVo = {
          detailId: currentDetailInfo.id,
          rawFileName: rawFileName,
          suffix: suffix,
          fileName: fileName,
          fileUrl: fileUrl,
          fileType: rawFile.file.type
        };
        savaAnnex(fileDataVo);
        groupFormulaList.push(fileDataVo);
      }
    })
    .catch((error) => {
      VxeMessage('上传过程中出现错误', VxeNotifyType.error);
    });
}

// 根据详情id获取附件列表
function getAnnexList() {
  groupFormulaList.length = 0;
  const url = '/wk/quality/detail/annex/getQualityDetailAnnexList';
  proxy.$http
    .get(url, { params: { detailId: currentDetailInfo.id } })
    .then((res: any) => {
      if (res.status.code === 1) {
        groupFormulaList.push(...res.data);
        nodeCount.value = nodeMap.value.get(currentDetailInfo.nodeId).uploadSum;
        showUpload.value = nodeCount.value > groupFormulaList.length;
      }
    })
    .catch((err) => {
      VxeMessage(err.response.data.status.msg, VxeNotifyType.error);
    });
}

function savaAnnex(fail: any) {
  const url = '/wk/quality/detail/annex/addQualityDetailAnnex';
  proxy.$http
    .post(url, fail)
    .then((res: any) => {
      if (res.status.code === 1) {
        VxeMessage('提交成功', VxeNotifyType.success);
        getAnnexList();
      } else {
        VxeMessage('提交失败', VxeNotifyType.error);
      }
    })
    .catch((err) => {
      VxeMessage(err.response.data.status.msg, VxeNotifyType.error);
    });
}

// 删除
function deleteAnnex() {
  const $xTable = proxy.$refs.groupTable as any;
  const selectRows = $xTable.getCheckboxRecords();
  if (selectRows.length <= 0) {
    VxeMessage('请先选中要删除的项', VxeNotifyType.warning);
    return;
  }
  proxy
    .$confirm('确定删除此项？', '提示', {
      cancelButtonClass: 'cancel-button',
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    .then((type) => {
      if (type === 'confirm') {
        let ids = selectRows.map((item) => item.id);
        const url = '/wk/quality/detail/annex/deleteQualityDetailAnnex';
        proxy.$http
          .post(url, ids)
          .then((res: any) => {
            if (res.status.code === 1) {
              VxeMessage('删除成功', VxeNotifyType.success);
              dbDetailModel(currentPlanInfo);
            } else {
              VxeMessage('删除失败', VxeNotifyType.error);
            }
          })
          .catch((err) => {
            VxeMessage(err.response.data.status.msg, VxeNotifyType.error);
          });
      }
    });
}

function showPdf(row: any) {
  pdfUrl.value = row.fileUrl;
  showTemplateDialog.value = true;
}

function clearData() {
  showUpload.value = true;
  groupFormulaList.length = 0;
}
</script>
<style lang="scss" scoped>
.qualityPlanDetailDiv {
  height: 100%;

  .attachmentAddressAll {
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: center;

    // 附件地址上传按钮
    .attachmentAddressUpload {
      display: inline-block;
    }

    .viewBtnsMore {
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      // align-items:flex-start;
      // flex-wrap: wrap;
    }

    // 小眼睛
    .viewBtn {
      margin: 0 0 5px 5px;
    }
  }
}
</style>

<style lang="scss">
// 计划详情dialog
.planDetailDialog {
  height: 600px;
  padding: 0;

  .el-dialog__header {
    padding: 20px;
  }

  .el-dialog__body {
    padding: 0;
    height: calc(100% - 65px);

    // 附加按钮间距
    .button-blue,
    .button-red {
      margin: 5px 0 5px 5px;
    }

    .tableBody {
      padding: 0 10px;
      height: calc(100% - 50px);
    }
  }
}
// 图片详情dialog
.imgDetailDialog {
  height: 800px;
}
</style>
